#!/usr/bin/env node
/* eslint-disable */
const fs = require('fs')
const path = require('path')

/**
 * 递归查找并删除指定扩展名的文件
 * @param {string} dir 目录路径
 * @param {string[]} extensions 扩展名数组，如 ['.yml', '.md']
 * @returns {string[]} 被删除的文件路径数组
 */
function deleteFilesByExtension(dir, extensions) {
  let deletedFiles = []

  try {
    const items = fs.readdirSync(dir)

    for (const item of items) {
      const fullPath = path.join(dir, item)
      const stat = fs.statSync(fullPath)

      if (stat.isDirectory()) {
        // 递归处理子目录
        const subDeleted = deleteFilesByExtension(fullPath, extensions)
        deletedFiles = deletedFiles.concat(subDeleted)
      } else if (stat.isFile()) {
        // 检查文件扩展名
        const ext = path.extname(item).toLowerCase()
        if (extensions.includes(ext)) {
          try {
            fs.unlinkSync(fullPath)
            deletedFiles.push(fullPath)
            console.log(`已删除: ${fullPath}`)
          } catch (error) {
            console.error(`删除文件失败 ${fullPath}:`, error.message)
          }
        }
      }
    }
  } catch (error) {
    console.error(`读取目录失败 ${dir}:`, error.message)
  }

  return deletedFiles
}

// 主函数
function main() {
  const srcDir = path.join(__dirname, 'src')
  const extensions = ['.yml', '.yaml', '.md']

  console.log('开始搜索并删除文件...')
  console.log(`目标目录: ${srcDir}`)
  console.log(`目标扩展名: ${extensions.join(', ')}`)
  console.log('---')

  const deletedFiles = deleteFilesByExtension(srcDir, extensions)

  console.log('---')
  if (deletedFiles.length === 0) {
    console.log('此次没有删除要项。')
  } else {
    console.log(`共删除 ${deletedFiles.length} 个文件`)
  }

  // 退出码：如果有错误或没有删除文件，返回 0（成功），因为这是正常情况
  process.exit(0)
}

main()
